package com.jiwei.community.utils;

import com.jiwei.community.enums.AppHttpCodeEnum;
import com.jiwei.community.exception.SystemException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 季伟
 * @date 2023/6/7 20:20
 * 功能：存储上传的文件
 */
@Component
public class UploadUtils {

    public static String path;
    @Value("${upload.path}")
    public void setPath(String path){
        UploadUtils.path = path;
    }
    public static String uploadAvatar(MultipartFile file){
        String avatarPath = path + "avatar\\";
        try{
            String realFileName = file.getOriginalFilename();
            if(!realFileName.endsWith(".png") && !realFileName.endsWith(".jpg") && !realFileName.endsWith(".jpeg")&& !realFileName.endsWith(".JPG")){
                throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
            }
            String imgSuffix = realFileName.substring(realFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + imgSuffix;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            File dirPath = new File(avatarPath,datePath);
            if(!dirPath.exists()){
                dirPath.mkdirs();
            }
            File targetFile = new File(dirPath,newFileName);
            file.transferTo(targetFile);
            return "/file/avatar/"+datePath+"/"+newFileName;
        }catch (IOException e){
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR,"图片保存失败");
        }
    }

    public static String uploadImage(MultipartFile file){
        String imagePath = path + "image\\";
        try{
            String realFileName = file.getOriginalFilename();
            if(!realFileName.endsWith(".png") && !realFileName.endsWith(".jpg") && !realFileName.endsWith(".jpeg")){
                throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
            }
            String imgSuffix = realFileName.substring(realFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + imgSuffix;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            File dirPath = new File(imagePath,datePath);
            if(!dirPath.exists()){
                dirPath.mkdirs();
            }
            File targetFile = new File(dirPath,newFileName);
            file.transferTo(targetFile);
            return "/file/image/"+datePath+"/"+newFileName;
        }catch (IOException e){
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR,"图片保存失败");
        }
    }
}
